package com.trigram.base.filter;

import com.trigram.base.filter.wrapper.ReuseRequestWrapper;
import com.trigram.base.filter.wrapper.ReuseResponseWrapper;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.servlet.filter.OrderedFilter;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class ReuseRequestWrapperFilter implements OrderedFilter {

  @Override
  public int getOrder() {
    //spring boot 默认扩展的过滤OrderedRequestContextFilter
    //它使用的是REQUEST_WRAPPER_FILTER_MAX_ORDER - 105
    //所以为了比它早一点
    return OrderedFilter.REQUEST_WRAPPER_FILTER_MAX_ORDER - 108;
  }

  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    //传递包装类下去。这样后面的servlet等可以拿到这个包装后的request
    if (log.isDebugEnabled()) {
      log.info("[{}]进入可重用请求过滤器", ((HttpServletRequest) request).getRequestURI());
    }
    ReuseResponseWrapper reuseResponse = new ReuseResponseWrapper((HttpServletResponse) response);
    ReuseRequestWrapper  reuseRequest  = new ReuseRequestWrapper((HttpServletRequest) request);
    chain.doFilter(reuseRequest, reuseResponse);
    // 在未调用这个方法之前，任何写入响应流的数据实际是写入到了缓存流中
    reuseResponse.copyBodyToResponse();
  }

}
